package org.amphiprion.descentv2assistant.dao.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.descentv2assistant.App;
import org.amphiprion.descentv2assistant.ApplicationConstants;
import org.amphiprion.descentv2assistant.entity.Language;
import org.amphiprion.descentv2assistant.util.PreferenceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.os.Environment;
import android.util.Log;

public class LanguageXmlDao extends AbstractXmlDao {
	private static LanguageXmlDao instance;

	public static LanguageXmlDao getInstance() {
		if (instance == null) {
			instance = new LanguageXmlDao();
		}
		return instance;
	}

	public List<Language> getLanguages() {
		if (App.languages != null) {
			return App.languages;
		}
		List<Language> result = new ArrayList<Language>();
		String lng = PreferenceUtil.getLanguage();
		InputStream is = null;
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/languages.xml");

			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
				is = App.class.getResourceAsStream("/languages.xml");
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);

			NodeList list = document.getElementsByTagName("lang");
			for (int i = 0; i < list.getLength(); i++) {
				Element productNode = (Element) list.item(i);
				String id = productNode.getAttributes().getNamedItem("id").getNodeValue();
				String name = productNode.getAttributes().getNamedItem("name").getNodeValue();

				Language language = new Language();
				language.setId(id);
				language.setName(name);

				result.add(language);
			}
			is.close();
			Collections.sort(result);
			App.languages = result;
			return result;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			if (is != null) {
				try {
					is.close();
				} catch (Throwable ex) {
				}
			}
			return null;
		}
	}

}
